package net.cyl.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import net.cyl.model.LoginUser;

import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Date;

@Slf4j
public class JWTUtil {

    // 定义主题
    private static final String SUBJECT = "cyl";

    public static final String SECRET = "caoyulindkfjewodifjherwdogwedifhjedwifewfewifhjeiuf";


    // 使用 JJWT 工具类生成符合 HS256 算法要求的密钥（256位）
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    // 如果你需要以字符串形式存储或打印密钥（用于配置文件/环境变量）
    public static final String SECRET_STRING = Base64.getEncoder().encodeToString(SECRET_KEY.getEncoded());

    // 定义token前缀
    public static final String TOKEN_PREFIX = "cloud-link";

    // 定义token过期时间
    public static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;
    // 生成token
    public static String generateToken(LoginUser loginUser) {
         if(loginUser == null){
             throw new IllegalArgumentException("对象为空");
         }
         String token = Jwts.builder().setSubject(SUBJECT)
                 .claim("accountNo", loginUser.getAccountNo())
                 .claim("username", loginUser.getUsername())
                 .claim("headImg", loginUser.getHeadImg())
                 .claim("mail", loginUser.getMail())
                 .claim("phone", loginUser.getPhone())
                 .claim("auth", loginUser.getAuth())
                 .setIssuedAt(new Date())
                 .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
         log.info("当前时间是{}",new Date());
         return TOKEN_PREFIX + token;

    }

    public static Claims parseToken(String token) {
        try  {
            log.info("token{}",token);
            return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                .getBody();
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("token解析失败");

            return null;
        }

    }
}
